<template>
  <div class="plant-detection-container">
    <!-- 左侧面板 -->
    <div class="left-panel">
      <!-- 图片上传区域 -->
      <div class="upload-card">
        <div class="card-header">
          <i class="el-icon-picture-outline"></i>
          <span>校园植物检测</span>
          <el-tooltip content="点击图片区域可重新上传" placement="top">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </div>
        <div class="upload-area" @click="handleUploadClick">
          <img v-if="imageUrl" :src="imageUrl" class="uploaded-image" />
          <div v-else class="upload-placeholder">
            <i class="el-icon-upload"></i>
            <div>点击上传植物图片</div>
          </div>
          <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleFileChange" />
        </div>
      </div>
  
      <!-- 检测结果区域 -->
      <div class="result-card">
        <div class="card-header">
          <i class="el-icon-document"></i>
          <span>检测结果</span>
          <el-tag v-if="detectionTime" size="mini" type="info">
            检测时间: {{ detectionTime }}
          </el-tag>
        </div>
        <el-table :data="detectionResults" stripe style="width: 100%" height="400px" v-loading="loading">
          <el-table-column prop="accuracy" label="置信度" width="120" sortable>
            <template slot-scope="{ row }">
              <div style="display: flex; align-items: center;">
                <el-progress :percentage="row.accuracy" :color="getProgressColor(row.accuracy)" :show-text="false"
                  :stroke-width="12" style="flex: 1; margin-right: 10px;" />
                <span>{{ row.accuracy }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="分类" width="150">
            <template slot-scope="{ row }">
              <el-tag :type="getPlantTypeColor(row.type)" size="small">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="植物名称" width="150">
            <template slot-scope="{ row }">
              <span :class="{ 'rare-text': row.rare }">
                {{ row.name }}
                <el-tag v-if="row.rare" size="mini" type="warning">稀有</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="desc" label="植物特征" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span v-if="row.desc">{{ row.desc }}</span>
              <span v-else class="no-desc">暂无描述</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click.stop="viewPlantInfo(row)">
                详情
              </el-button>
              <el-button type="text" size="small" @click.stop="confirmDelete(row, $index)" style="color: red">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  
    <!-- 右侧面板 -->
    <div class="right-panel">
      <!-- 搜索区域 -->
      <div class="search-card">
        <div class="card-header">
          <i class="el-icon-search"></i>
          <span>植物搜索</span>
        </div>
        <div class="search-box">
          <el-input v-model="searchQuery" placeholder="输入植物名称搜索" clearable @keyup.enter.native="handleSearch"
            @clear="handleClearHistory">
            <i slot="prefix" class="el-icon-search"></i>
          </el-input>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch" :loading="searchLoading">
            搜索
          </el-button>
        </div>
      </div>
  
      <!-- 历史记录区域 -->
      <div class="history-card">
        <div class="card-header">
          <i class="el-icon-time"></i>
          <span>检测历史</span>
          <el-button type="text" size="mini" @click="clearHistory" :disabled="historyData.length === 0">
            清空历史
          </el-button>
        </div>
        <el-table :data="historyData" height="100%" style="width: 100%" empty-text="暂无检测历史">
          <el-table-column prop="time" label="检测时间" width="180">
            <template slot-scope="{ row }">
              <el-tooltip :content="row.time" placement="top">
                <span>{{ formatTime(row.time) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="检测结果">
            <template slot-scope="{ row }">
              <div class="result-summary">
                <span v-for="(item, index) in row.results" :key="index">
                  <span>{{ item.name }}</span>
                  <span v-if="index < row.results.length - 1">, </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click.stop="viewHistoryDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  
    <!-- 上传对话框 -->
    <el-dialog :visible.sync="uploadDialogVisible" title="上传昆虫图片" width="500px" :close-on-click-modal="false">
      <el-upload class="upload-dialog" drag action="#" :auto-upload="false" :show-file-list="false"
        :on-change="handleDialogUpload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          支持JPG/PNG格式，大小不超过5MB
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpload" :disabled="!selectedFile" :loading="uploadLoading">
          确认上传
        </el-button>
      </div>
    </el-dialog>
  
  
    <!--详情 -->
    <el-dialog :visible.sync="textDetail" :title="baikeDetail.title" width="800px" :close-on-click-modal="false" center>
      <div class="baike-content" style="max-height: 600px; overflow-y: auto; padding: 24px;">
        <h3 style="font-weight:bold; font-size:20px; margin-bottom:16px;">{{ baikeDetail.title }}</h3>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.summary }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">基本信息</h4>
        <table style="width:100%; font-size:14px; margin-bottom:18px; border-collapse:collapse;">
          <tr v-for="(row, idx) in baikeDetail.baseInfo" :key="idx">
            <td style="width:80px; color:#888;">{{ row[0] }}</td>
            <td>{{ row[1] }}</td>
            <td style="width:80px; color:#888;">{{ row[2] }}</td>
            <td>{{ row[3] }}</td>
          </tr>
        </table>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">形态特征</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.feature }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">生活习性</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.habit }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">分布范围</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.distribution }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">繁殖方式</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.reproduction }}
        </div>
        <h4 style="font-weight:bold; margin: 12px 0 8px 0;">防治方法</h4>
        <div style="margin-bottom: 18px; line-height: 1.8; color: #333;">
          {{ baikeDetail.control }}
        </div>
      </div>
    </el-dialog>
  
    <el-dialog title="提示" :visible.sync="deleteDialogVisible" width="300px" :close-on-click-modal="false">
      <span>确定要删除该条数据吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDelete">取消</el-button>
        <el-button type="primary" @click="handleDelete">确定</el-button>
      </span>
    </el-dialog>
  
  </div>
</template>

<script>
export default {
  name: 'PlantDetection',
  data() {
    return {
      imageUrl: '',
      searchQuery: '',
      loading: false,
      searchLoading: false,
      uploadDialogVisible: false,
      textDetail: false,
      selectedFile: null,
      baikeDetail: {},
      detectionTime: this.getCurrentDateTime(),
      detectionResults: [
        { accuracy: 94.35, type: '乔木', name: '银杏', rare: true, desc: '银杏为落叶大乔木，叶扇形，有长柄，秋季变黄，是现存种子植物中最古老的孑遗植物' },
        { accuracy: 88.20, type: '灌木', name: '月季', rare: false, desc: '常绿或半常绿灌木，小枝绿色，散生皮刺，花多重瓣，花色丰富' },
        { accuracy: 76.45, type: '草本', name: '三色堇', rare: false, desc: '一年生或短期多年生草本，花大，通常每花有紫、白、黄三色' },
        { accuracy: 65.30, type: '藤本', name: '紫藤', rare: false, desc: '落叶藤本，茎左旋，羽状复叶，总状花序下垂，花紫色或深紫色' },
        { accuracy: 52.10, type: '乔木', name: '水杉', rare: true, desc: '落叶乔木，小枝对生，叶线形，交互对生，是珍贵的孑遗植物' }
      ],
      historyData: [
        {
          time: this.getCurrentDateTime(),
          results: [
            { name: '银杏', type: '乔木' },
            { name: '月季', type: '灌木' }
          ]
        },
        {
          time: this.getPastDateTime(1),
          results: [
            { name: '紫藤', type: '藤本' }
          ]
        }
      ],
      baikeMap: {
        '银杏': {
          title: '银杏百科',
          summary: '银杏为落叶大乔木，叶扇形，有长柄，秋季变黄，是现存种子植物中最古老的孑遗植物。',
          baseInfo: [
            ['别名', '白果树', '科', '银杏科'],
            ['中文学名', '银杏', '属', '银杏属'],
            ['拉丁学名', 'Ginkgo biloba', '分布', '中国、朝鲜、日本等'],
            ['门', '裸子植物门', '寿命', '可达千年'],
          ],
          feature: '叶片扇形，秋季变黄，种子称为白果。',
          habit: '喜光，耐寒，适应性强。',
          distribution: '中国、朝鲜、日本等地广泛分布。',
          reproduction: '种子繁殖，扦插繁殖。',
          control: '主要病虫害有银杏叶螨、银杏炭疽病等，需及时防治。'
        },
        '月季': {
          title: '月季百科',
          summary: '月季为常绿或半常绿灌木，小枝绿色，散生皮刺，花多重瓣，花色丰富。',
          baseInfo: [
            ['别名', '月月红', '科', '蔷薇科'],
            ['中文学名', '月季', '属', '蔷薇属'],
            ['拉丁学名', 'Rosa chinensis', '分布', '中国、世界各地'],
            ['门', '被子植物门', '寿命', '多年生'],
          ],
          feature: '花色丰富，花期长，枝条有皮刺。',
          habit: '喜光，耐旱，适应性强。',
          distribution: '中国及世界各地广泛栽培。',
          reproduction: '扦插、分株、嫁接繁殖。',
          control: '常见病虫害有白粉病、蚜虫等。'
        },
        '三色堇': {
          title: '三色堇百科',
          summary: '三色堇为一年生或短期多年生草本，花大，通常每花有紫、白、黄三色。',
          baseInfo: [
            ['别名', '蝴蝶花', '科', '堇菜科'],
            ['中文学名', '三色堇', '属', '堇菜属'],
            ['拉丁学名', 'Viola tricolor', '分布', '欧洲、亚洲'],
            ['门', '被子植物门', '寿命', '一年或多年生'],
          ],
          feature: '花色三色，花型美丽。',
          habit: '喜光，耐寒，适应性强。',
          distribution: '欧洲、亚洲等地。',
          reproduction: '种子繁殖。',
          control: '主要病虫害有蚜虫、白粉病等。'
        },
        '紫藤': {
          title: '紫藤百科',
          summary: '紫藤为落叶藤本，茎左旋，羽状复叶，总状花序下垂，花紫色或深紫色。',
          baseInfo: [
            ['别名', '藤萝', '科', '豆科'],
            ['中文学名', '紫藤', '属', '紫藤属'],
            ['拉丁学名', 'Wisteria sinensis', '分布', '中国、日本'],
            ['门', '被子植物门', '寿命', '多年生'],
          ],
          feature: '花序下垂，花色紫或深紫。',
          habit: '喜光，耐寒，适应性强。',
          distribution: '中国、日本等地。',
          reproduction: '种子、扦插繁殖。',
          control: '主要病虫害有紫藤尺蠖、蚜虫等。'
        },
        '水杉': {
          title: '水杉百科',
          summary: '水杉为落叶乔木，小枝对生，叶线形，交互对生，是珍贵的孑遗植物。',
          baseInfo: [
            ['别名', '落羽杉', '科', '杉科'],
            ['中文学名', '水杉', '属', '水杉属'],
            ['拉丁学名', 'Metasequoia glyptostroboides', '分布', '中国'],
            ['门', '被子植物门', '寿命', '多年生'],
          ],
          feature: '叶线形，小枝对生。',
          habit: '喜光，耐湿，适应性强。',
          distribution: '中国特有，分布于长江流域。',
          reproduction: '种子繁殖。',
          control: '主要病虫害有水杉毛虫等。'
        }
      },
      deleteDialogVisible: false,
      deleteRow: null,
      deleteIndex: null,
    }
  },
  methods: {
    // 获取当前日期时间
    getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 获取过去某天的日期时间
    getPastDateTime(days) {
      const date = new Date();
      date.setDate(date.getDate() - days);
      return this.getCurrentDateTime(date);
    },

    // 格式化时间显示
    formatTime(timeString) {
      const date = new Date(timeString);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${month}-${day} ${hours}:${minutes}`;
    },

    // 根据植物类型返回标签颜色
    getPlantTypeColor(type) {
      const typeColors = {
        '乔木': 'success',
        '灌木': '',
        '草本': 'info',
        '藤本': 'warning',
        '水生植物': 'primary'
      };
      return typeColors[type] || '';
    },

    // 查看植物详情
    viewPlantInfo(row) {
      this.baikeDetail = this.baikeMap[row.name] || {
        title: row.name + '百科',
        summary: row.desc || '',
        baseInfo: [],
        feature: '',
        habit: '',
        distribution: '',
        reproduction: '',
        control: ''
      };
      this.textDetail = true;
    },

    // 其他方法保持不变...
    handleUploadClick() {
      this.uploadDialogVisible = true;
    },
    handleFileChange(e) {
      const file = e.target.files[0];
      if (file) {
        this.previewImage(file);
      }
    },
    handleDialogUpload(file) {
      this.selectedFile = file;
      this.previewImage(file.raw);
    },
    previewImage(file) {
      if (!file.type.match('image.*')) {
        this.$message.error('请选择图片文件');
        return;
      }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('图片大小不能超过5MB');
        return;
      }
      const reader = new FileReader();
      reader.onload = (e) => {
        this.imageUrl = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    confirmUpload() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择图片');
        return;
      }
      this.loading = true;
      this.uploadDialogVisible = false;
      setTimeout(() => {
        this.detectionTime = this.getCurrentDateTime();
        this.historyData.unshift({
          time: this.detectionTime,
          results: this.detectionResults.map(item => ({
            name: item.name,
            type: item.type
          }))
        });
        this.loading = false;
        this.$message.success('检测完成');
      }, 1500);
    },
    handleSearch() {
      if (!this.searchQuery.trim()) {
        this.$message.warning('请输入搜索内容');
        return;
      }
      this.searchLoading = true;
      setTimeout(() => {
        this.searchLoading = false;
        // this.$message.success(`搜索: ${this.searchQuery}`);
        this.historyData = this.historyData.filter(item =>
          item.results.some(result => result.name.includes(this.searchQuery))
        );
      }, 800);
    },
    handleClearHistory() {
      this.historyData = this.historyData_pass;
    },
    viewHistoryDetail(row) {
      this.$message.info(`查看历史详情: ${row.time}`);
    },
    clearHistory() {
      this.$confirm('确定要清空所有检测历史吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.historyData = [];
        this.$message.success('历史记录已清空');
      }).catch(() => { });
    },
    getProgressColor(percentage) {
      if (percentage > 90) return '#67C23A';
      if (percentage > 70) return '#409EFF';
      if (percentage > 50) return '#E6A23C';
      return '#F56C6C';
    },
    confirmDelete(row, index) {
      this.deleteDialogVisible = true;
      this.deleteRow = row;
      this.deleteIndex = index;
    },
    handleDelete() {
      this.detectionResults.splice(this.deleteIndex, 1);
      this.deleteDialogVisible = false;
      this.deleteRow = null;
      this.deleteIndex = null;
      this.$message.success('删除成功');
    },
    cancelDelete() {
      this.deleteDialogVisible = false;
      this.deleteRow = null;
      this.deleteIndex = null;
    },
  }
}
</script>

<style>
.plant-detection-container {
  display: flex;
  height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f5f7fa;
  position: relative;
  gap: 20px;
}

.plant-detection-container .left-panel {
  flex: 0 0 60%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.plant-detection-container .right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.plant-detection-container .card-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8f9fa;
  border-radius: 4px 4px 0 0;
  font-weight: 500;
  color: #333;
}

.plant-detection-container .card-header i {
  margin-right: 8px;
  font-size: 16px;
}

.plant-detection-container .card-header .el-tag,
.plant-detection-container .card-header .el-button {
  margin-left: auto;
}

.plant-detection-container .upload-card,
.plant-detection-container .result-card,
.plant-detection-container .search-card,
.plant-detection-container .history-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.plant-detection-container .upload-card .upload-area {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 300px;
}

.plant-detection-container .upload-card .upload-area:hover {
  background-color: #f5f7fa;
}

.plant-detection-container .upload-card .uploaded-image {
  max-width: 100%;
  max-height: 300px;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.plant-detection-container .upload-card .upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #909399;
}

.plant-detection-container .upload-card .upload-placeholder i {
  font-size: 48px;
  margin-bottom: 16px;
}

.plant-detection-container .result-card {
  flex: 1;
}

.plant-detection-container .result-card .el-table {
  flex: 1;
}

.plant-detection-container .result-card .rare-text {
  color: #e6a23c;
  font-weight: 500;
}

.plant-detection-container .result-card .no-desc {
  color: #c0c4cc;
  font-style: italic;
}

.plant-detection-container .result-card .el-progress {
  display: inline-block;
  width: 60px;
  margin-right: 8px;
  vertical-align: middle;
}

.plant-detection-container .search-card .search-box {
  padding: 20px;
  display: flex;
  gap: 10px;
}

.plant-detection-container .search-card .search-box .el-input {
  flex: 1;
}

.plant-detection-container .history-card {
  flex: 1;
}

.plant-detection-container .history-card .el-table {
  flex: 1;
}

.plant-detection-container .history-card .result-summary {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.upload-dialog {
  text-align: center;
  padding: 20px;
}

.upload-dialog .el-upload-dragger {
  padding: 40px 20px;
}

.upload-dialog .el-upload__tip {
  margin-top: 10px;
  color: #909399;
}

@media (max-width: 992px) {
  .plant-detection-container {
    flex-direction: column;
    height: auto;
  }

  .plant-detection-container .left-panel,
  .plant-detection-container .right-panel {
    flex: 1 1 100%;
  }
}
</style>